package com.zhuoan.framework.config;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Swagger2的接口配置
 *
 * @author ruoyi
 */
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class SwaggerConfig {

    private final static Logger logger = LoggerFactory.getLogger(SwaggerConfig.class);

    /**
     * 系统基础配置
     */
    @Autowired
    private RuoYiConfig ruoYiConfig;

    @Value("${server.port}")
    private String port;

    /**
     * 创建API
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
            // 详细定制
            .apiInfo(apiInfo())
            .select()
            // 指定当前包路径
            .apis(RequestHandlerSelectors.basePackage("com.zhuoan.project.tool.swagger"))
            // 扫描所有 .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build();
    }


    /**
     * 添加摘要信息
     */
    private ApiInfo apiInfo() {
        String hostAddress = null;
        try {
            InetAddress address = InetAddress.getLocalHost();
            hostAddress = address.getHostAddress();
        } catch (UnknownHostException e) {
            logger.error("获取本地主机地址异常", e);
        }
        // 用ApiInfoBuilder进行定制
        return new ApiInfoBuilder()
            .title("卓安后台管理系统之API接口文档中心")
            .description("用于管理XXX信息,具体包括XXX,XXX模块...")
            // 配置联系人
            .contact(new Contact(ruoYiConfig.getName(), null, null))
            // 配置版本
            .version(ruoYiConfig.getVersion())
            // 获取ip和port
            .termsOfServiceUrl(String.format("http://%s:%s", hostAddress, port))
            .build();
    }
}


